<template>
  <div class="requirements-page">
    <div class="page-header">
      <h1>需求管理</h1>
      <p>管理您的需求项目，跟踪测试用例和执行结果</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <el-button type="primary" @click="showCreateDialog = true">
        <el-icon><Plus /></el-icon>
        新建需求
      </el-button>
      
      <div class="search-bar">
        <el-input
          v-model="searchText"
          placeholder="搜索需求..."
          @input="handleSearch"
          style="width: 300px"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 需求列表 -->
    <el-card class="requirements-list">
      <el-table :data="requirementsList" stripe v-loading="loading">
        <el-table-column prop="title" label="需求标题" min-width="200">
          <template #default="scope">
            <div class="requirement-title">
              <span @click="viewDetail(scope.row)" class="title-link">
                {{ scope.row.title }}
              </span>
              <el-tag v-if="scope.row.tags && scope.row.tags.length > 0" 
                     size="small" 
                     class="tag-item">
                {{ scope.row.tags[0] }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="description" label="描述" min-width="300">
          <template #default="scope">
            <div class="description-text">
              {{ scope.row.description || '暂无描述' }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">
              {{ getPriorityText(scope.row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="editRequirement(scope.row)">
              编辑
            </el-button>
            <el-button type="success" size="small" @click="generateTestCases(scope.row)">
              生成用例
            </el-button>
            <el-button type="danger" size="small" @click="deleteRequirement(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑需求对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      :title="editingRequirement ? '编辑需求' : '新建需求'"
      width="600px"
    >
      <el-form
        ref="requirementFormRef"
        :model="requirementForm"
        :rules="requirementRules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="requirementForm.title" placeholder="请输入需求标题" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="requirementForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入需求描述"
          />
        </el-form-item>
        
        <el-form-item label="详细内容" prop="content">
          <el-input
            v-model="requirementForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入详细的需求内容"
          />
        </el-form-item>
        
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="requirementForm.priority" placeholder="请选择优先级">
            <el-option label="低" :value="1" />
            <el-option label="中" :value="2" />
            <el-option label="高" :value="3" />
            <el-option label="紧急" :value="4" />
            <el-option label="非常紧急" :value="5" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标签" prop="tags">
          <el-input v-model="tagsInput" placeholder="请输入标签，用逗号分隔" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateDialog = false">取消</el-button>
          <el-button type="primary" @click="saveRequirement" :loading="saving">
            {{ editingRequirement ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import { ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { requirementsApi } from '@/api/requirements'

const router = useRouter()
const toast = useToast()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const requirementsList = ref([])
const searchText = ref('')
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 对话框控制
const showCreateDialog = ref(false)
const editingRequirement = ref(null)
const requirementFormRef = ref()

// 表单数据
const requirementForm = reactive({
  title: '',
  description: '',
  content: '',
  priority: 2,
  tags: []
})

const tagsInput = ref('')

// 表单验证规则
const requirementRules = {
  title: [
    { required: true, message: '请输入需求标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入需求内容', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ]
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'active': 'success',
    'archived': 'info',
    'deleted': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'active': '活跃',
    'archived': '已归档',
    'deleted': '已删除'
  }
  return statusMap[status] || '未知'
}

// 获取优先级类型
const getPriorityType = (priority) => {
  const priorityMap = {
    1: 'info',
    2: 'success',
    3: 'warning',
    4: 'danger',
    5: 'danger'
  }
  return priorityMap[priority] || 'info'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  const priorityMap = {
    1: '低',
    2: '中',
    3: '高',
    4: '紧急',
    5: '非常紧急'
  }
  return priorityMap[priority] || '未知'
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

// 加载需求列表
const loadRequirements = async () => {
  loading.value = true
  try {
    const response = await requirementsApi.getRequirements({
      page: currentPage.value,
      page_size: pageSize.value,
      search: searchText.value
    })
    
    if (response && response.data) {
      const items = response.data.items || response.data
      requirementsList.value = Array.isArray(items) ? items : []
      total.value = response.data.total || requirementsList.value.length
    } else {
      requirementsList.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载需求列表失败:', error)
    toast.error('加载需求列表失败')
    requirementsList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  loadRequirements()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  loadRequirements()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  loadRequirements()
}

// 查看详情
const viewDetail = (requirement) => {
  // 可以实现详情页面或弹窗
  console.log('查看详情:', requirement)
}

// 编辑需求
const editRequirement = (requirement) => {
  editingRequirement.value = requirement
  requirementForm.title = requirement.title
  requirementForm.description = requirement.description || ''
  requirementForm.content = requirement.content || ''
  requirementForm.priority = requirement.priority
  requirementForm.tags = requirement.tags || []
  tagsInput.value = requirement.tags ? requirement.tags.join(', ') : ''
  showCreateDialog.value = true
}

// 保存需求
const saveRequirement = async () => {
  if (!requirementFormRef.value) return
  
  try {
    await requirementFormRef.value.validate()
    
    saving.value = true
    
    // 处理标签
    const tags = tagsInput.value
      .split(',')
      .map(tag => tag.trim())
      .filter(tag => tag.length > 0)
    
    const requirementData = {
      ...requirementForm,
      tags
    }
    
    if (editingRequirement.value) {
      // 更新需求
      await requirementsApi.updateRequirement(editingRequirement.value.id, requirementData)
      toast.success('需求更新成功')
    } else {
      // 创建需求
      await requirementsApi.createRequirement(requirementData)
      toast.success('需求创建成功')
    }
    
    showCreateDialog.value = false
    resetForm()
    loadRequirements()
    
  } catch (error) {
    console.error('保存需求失败:', error)
    toast.error(error.response?.data?.detail || '保存需求失败')
  } finally {
    saving.value = false
  }
}

// 删除需求
const deleteRequirement = async (requirement) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除需求"${requirement.title}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await requirementsApi.deleteRequirement(requirement.id)
    toast.success('需求删除成功')
    loadRequirements()
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除需求失败:', error)
      toast.error(error.response?.data?.detail || '删除需求失败')
    }
  }
}

// 生成测试用例
const generateTestCases = (requirement) => {
  // 跳转到测试用例生成页面，并传递需求内容
  router.push({
    path: '/test-cases',
    query: {
      requirement_id: requirement.id,
      requirement_text: requirement.content
    }
  })
}

// 重置表单
const resetForm = () => {
  editingRequirement.value = null
  requirementForm.title = ''
  requirementForm.description = ''
  requirementForm.content = ''
  requirementForm.priority = 2
  requirementForm.tags = []
  tagsInput.value = ''
  
  if (requirementFormRef.value) {
    requirementFormRef.value.resetFields()
  }
}

onMounted(() => {
  loadRequirements()
})
</script>

<style lang="scss" scoped>
.requirements-page {
  padding: 20px;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.requirements-list {
  .requirement-title {
    display: flex;
    align-items: center;
    gap: 10px;
    
    .title-link {
      color: #409eff;
      cursor: pointer;
      
      &:hover {
        text-decoration: underline;
      }
    }
    
    .tag-item {
      margin-left: 8px;
    }
  }
  
  .description-text {
    max-width: 300px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 